package com.kkwrite.regimen.provider.service.login;

import com.kkwrite.regimen.common.entity.dto.login.ChangePasswordInDTO;
import com.kkwrite.regimen.common.entity.dto.login.CheckPasswordInDTO;
import com.kkwrite.regimen.common.entity.dto.login.ShopLoginInDTO;
import com.kkwrite.regimen.provider.domain.RegEmployeeDO;
import com.kkwrite.regimen.provider.repository.RegEmployeeRepository;
import com.kkwrite.regimen.provider.util.TokenUtil;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.Clock;
import java.util.Optional;

/**
 * Created by lisha on 2018/8/16 14:27.
 *
 * @author lisha
 */
@Service(value = "loginService")
@Transactional(rollbackFor = Exception.class)
public class LoginServiceImpl implements LoginService {

    @Resource(name = "regEmployeeRepository")
    private RegEmployeeRepository employeeRepository;
    @Resource(name = "tokenUtil")
    private TokenUtil tokenUtil;

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = true)
    public String shopLogin(ShopLoginInDTO inDTO) {
        RegEmployeeDO example = new RegEmployeeDO();
        if (StringUtils.isNotBlank(inDTO.getUsername())) {
            example.setEmployeeName(inDTO.getUsername());
        }
        if (StringUtils.isNotBlank(inDTO.getPhoneNum())) {
            example.setPhoneNum(inDTO.getPhoneNum());
        }
        Optional<RegEmployeeDO> optional = employeeRepository.findOne(Example.of(example));
        RegEmployeeDO employee = optional.orElseThrow(() -> new RuntimeException("账户不存在"));
        if (!employee.getPassword().equals(inDTO.getPassword())) {
            throw new RuntimeException("账户或密码不正确");
        }
        String token = tokenUtil.existToken(String.valueOf(employee.getEmployeeId()));
        if (token != null) {
            tokenUtil.updateToken(token, employee.getPhoneNum(), employee.getEmployeeName(),
                    String.valueOf(employee.getEmployeeId()),  String.valueOf(employee.getShopId()));
            return token;
        }
        token = generateToken(inDTO.getPhoneNum(), inDTO.getUsername(), inDTO.getPassword());
        tokenUtil.catchLoginStatus(token, employee.getPhoneNum(), employee.getEmployeeName(),
                String.valueOf(employee.getEmployeeId()),  String.valueOf(employee.getShopId()));
        return token;
    }

    private String generateToken(String phoneNum, String username, String password) {
        String string = "";
        if (StringUtils.isBlank(phoneNum)) {
            string += "phoneNum" + "";
        }
        if (StringUtils.isBlank(username)) {
            string += "username" + "";
        }
        string += "password" + password;
        string += "millisecond" + Clock.systemDefaultZone().millis();
        return DigestUtils.md5Hex(string).toUpperCase();
    }

	@Override
	public String checkPassword(CheckPasswordInDTO inDto) {
		RegEmployeeDO example = new RegEmployeeDO();
		 if (StringUtils.isNotBlank(inDto.getUsername())) {
	            example.setEmployeeName(inDto.getUsername());
	        }
		 if (StringUtils.isNotBlank(inDto.getPhoneNum())) {
	            example.setPhoneNum(inDto.getPhoneNum());
	        }
		 if (StringUtils.isNotBlank(inDto.getPassword())) {
	            example.setPassword(inDto.getPassword());
	        }
		RegEmployeeDO regEmployeeDO = employeeRepository.findOne(Example.of(example)).orElse(null);
		if (regEmployeeDO != null) {
			return "success";
		} else {
			return "false";
		}
	}

	@Override
	public String changePassword(ChangePasswordInDTO inDto) {
		RegEmployeeDO example = new RegEmployeeDO();
		 if (StringUtils.isNotBlank(inDto.getUsername())) {
	            example.setEmployeeName(inDto.getUsername());
	        }
		 if (StringUtils.isNotBlank(inDto.getPhoneNum())) {
	            example.setPhoneNum(inDto.getPhoneNum());
	        }
		 RegEmployeeDO regEmployeeDO = employeeRepository.findOne(Example.of(example)).orElseThrow(RuntimeException::new);
		 if (StringUtils.isNotBlank(inDto.getPassword())) {
			 regEmployeeDO.setPassword(inDto.getPassword());
	        }
	        employeeRepository.saveAndFlush(regEmployeeDO);
		return "sucess";
	}

}
